package gui;

import javax.swing.AbstractButton;
import javax.swing.JPanel;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.KeyListener;

import javax.swing.JLabel;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Event;
import java.awt.Font;
import java.awt.Graphics;

import javax.swing.JSeparator;

import Entity.User;
import controllers.LibrarianUIP;
import controllers.OBLSettings;
import controllers.SubscriberUIP;
import controllers.WelcomeUIP;

import java.awt.Button;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.Observer;

import javax.swing.AbstractAction;
import javax.swing.DefaultListModel;
import javax.swing.InputMap;
import javax.swing.JComboBox;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.JTextArea;
import javax.swing.JTextPane;
import javax.swing.KeyStroke;
import javax.swing.ScrollPaneConstants;
import javax.swing.SwingConstants;
import javax.swing.border.MatteBorder;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.text.DefaultEditorKit;
import javax.swing.text.TabExpander;
import javax.swing.JToggleButton;
import javax.swing.ButtonGroup;

import messagesPacks.BookSubjectMessage;
import messagesPacks.LibrarianReturnBookMessage;
import messagesPacks.LibrarianSearchCopyMessage;
import messagesPacks.LibrarianSearchUserMessage;
import javax.swing.JTabbedPane;
import java.awt.event.MouseListener;
import java.awt.event.KeyEvent;

/**
 * This class representing a Librarian Gui
 * Date: 25/12/2012
 * @author Tali Pisarev & Alon Shahaf
 *
 */


public  class LibrarianUI extends JPanel 
{
	SubscriberUIP subscriberUIP;
	LibrarianViewHistory librarianViewHistory=null;
    LibrarianAddEditBookUI librarianAddEditBookPanel=null;
    LibrarianAddEditUserUI librarianAddEditUserPanel=null;
    LibrarianAddEditCopyUI librarianAddEditCopyPanel=null;
    LibrarianSearchBookUI librarianSearchBookPanel=null;
	SearchBooksUI searchBookPanel=null;
	private  LibrarianUIP luip=null;
	private final JSeparator separator = new JSeparator();
	private JLabel lblOblLibrarin;
	private JButton btnSearchBooks;
	JButton btnLogout;
	JButton btnExit;
	private JSeparator separator_1;
	private DefaultListModel<String> lstActivityLogOBJ;
	private JList lstActivityLog;
	SearchBooksUI book=null;
	public String op_user;
	public String op_Book;
	public String op_Copy;
	
	/**searchResultTable displays the search result of user*/
	public SimpleTable searchResultTable ;
	/**searchResultTableCopy displays the search result of copy*/
	public SimpleTable searchResultTableCopy;
	/**searchResultTableBook displays the search result of book*/
	
	public SimpleTable searchResultTableBook;
	private JToggleButton tglbtnUsers;
	private JToggleButton tglbtnBooks;
	private JToggleButton tglbtnCopies;	
    JTextField textField;
	private JButton btnSearch;
	JButton btnEdit;
	JButton btnAdd;
	JButton btnRemove;
	JLabel lblInsertUserid;
	JLabel lblInsertBookISBN;
	JLabel lblInsertCopyID;
	JButton btnBorrow;
	JButton btnReturn;
	
	/**flagArr for recognize the type of operation (user,copy,book)*/
	public int [] flagArr = new int[3];
	JButton btnHistory;
	
	private JLabel backgroundlabel;
	private JButton btnClear;
    JLabel Welcome_label;

//===============================================================================================
//	 Constructor
//	 
/**
* Constructor the LibrarianUI with default values
*
*/
	public LibrarianUI() 
	{
		super();
		this.luip=new LibrarianUIP();
		initialize();
	}
	private void initialize()
	{
	
		this.setSize(OBLSettings.pane2Size[0],OBLSettings.pane2Size[1]);
		setLayout(null);
		
		for(int i = 0 ;i < flagArr.length-1 ; i++)
		 flagArr[i] = 0;
		flagArr[2]=1;
		
		lblOblLibrarin = new JLabel("OBL Librarian");
		lblOblLibrarin.setFont(new Font("Tahoma", Font.BOLD, 20));
		lblOblLibrarin.setBounds(317, 0, 165, 58);
		add(lblOblLibrarin);
		
		btnLogout = new JButton("Logout");
		btnLogout.setFont(new Font("Tahoma", Font.BOLD, 15));
		btnLogout.setBounds(614, 11, 83, 41);
		add(btnLogout);
		
		btnExit = new JButton("Exit");
		
		btnExit.setFont(new Font("Tahoma", Font.BOLD, 15));
		btnExit.setBounds(707, 11, 83, 41);
		add(btnExit);
		
		this.op_user ="AddUser";
		this.op_Book="AddBook";
		this.op_Copy="AddCopy";

		this.librarianAddEditBookPanel=new LibrarianAddEditBookUI(getLibrarianUI());
		this.librarianAddEditUserPanel=new LibrarianAddEditUserUI(getLibrarianUI());
		this.librarianAddEditCopyPanel=new LibrarianAddEditCopyUI(getLibrarianUI());
		this.librarianSearchBookPanel=new LibrarianSearchBookUI(getLibrarianUI());
		
		separator_1 = new JSeparator();
		separator_1.setOrientation(SwingConstants.VERTICAL);
		separator_1.setBounds(584, 56, 45, 207);
		add(separator_1);
		
		//user table
		Object ColNames[] = { "ID", "First Name", "Last Name","Address","Email","Phone Number","Status"};
		searchResultTable = new SimpleTable(null, ColNames, 10, 285, 775, 220);
		searchResultTable.setColWidth(0,20);
		searchResultTable.setColWidth(1,50);
		searchResultTable.setColWidth(2,50);
		searchResultTable.setColWidth(3,60);
		searchResultTable.setColWidth(4,80);
		searchResultTable.setColWidth(5,150);
		searchResultTable.setColWidth(6,20);
		searchResultTable.table.setOpaque(false);

	    add(searchResultTable.tblScrollPane,BorderLayout.CENTER);
	    
	    //copy table
	    Object ColNamesCopy[] = { "CopyID", "ISBN", "Borrow","PurchaseDate" };
		searchResultTableCopy = new SimpleTable(null, ColNamesCopy, 10, 285, 775, 220);
		searchResultTableCopy.setColWidth(0,20);
		searchResultTableCopy.setColWidth(1,50);
		searchResultTableCopy.setColWidth(2,50);
		searchResultTableCopy.table.setOpaque(false);

	    add(searchResultTableCopy.tblScrollPane,BorderLayout.CENTER);
	    
	    //book table
	    Object ColBook[] = { "ISBN", "Book Name", "Author Name","Edition Number","Publish Year","Description","Shelf Location","Wanted"};
	    searchResultTableBook = new SimpleTable(null, ColBook, 10, 285, 775, 220);
	    searchResultTableBook.setColWidth(0,20);
	    searchResultTableBook.setColWidth(1,50);
	    searchResultTableBook.setColWidth(2,50);
	    searchResultTableBook.setColWidth(3,50);
	    searchResultTableBook.setColWidth(4,50);
	    searchResultTableBook.setColWidth(5,100);
	    searchResultTableBook.setColWidth(6,70);
	    searchResultTableBook.setColWidth(7,20);
	    searchResultTableBook.table.setOpaque(false);
		
		add(searchResultTableBook.tblScrollPane,BorderLayout.CENTER);
		
		
		ButtonGroup buttonGroup = new ButtonGroup();
		tglbtnUsers = new JToggleButton("Users");
		buttonGroup.add(tglbtnUsers);
		tglbtnUsers.setBounds(661, 69, 83, 41);
		tglbtnUsers.setFont(new Font("Tahoma", Font.BOLD, 15));
		tglbtnUsers.setActionCommand("Users");
		add(tglbtnUsers);
		
		tglbtnBooks = new JToggleButton("Books");
		buttonGroup.add(tglbtnBooks);
		tglbtnBooks.setActionCommand("Books");
		tglbtnBooks.setBounds(661, 137, 83, 41);
		tglbtnBooks.setFont(new Font("Tahoma", Font.BOLD, 15));
		add(tglbtnBooks);
		
		tglbtnCopies = new JToggleButton("Copies");
		buttonGroup.add(tglbtnCopies);
		tglbtnCopies.setBounds(661, 208, 83, 41);
		tglbtnCopies.setFont(new Font("Tahoma", Font.BOLD, 15));
		tglbtnCopies.setActionCommand("Copies");
		tglbtnCopies.setSelected(true);
		add(tglbtnCopies);

		JSeparator separator_3 = new JSeparator();
		separator_3.setBounds(0, 263, 855, 2);
		add(separator_3);
		separator.setBounds(0, 56, 855, 2);
		add(separator);
		
		textField = new JTextField();
		textField.setBounds(52, 227, 86, 25);
		add(textField);
		textField.setColumns(10);
		
		lblInsertUserid = new JLabel("Insert UserID");
		lblInsertUserid.setFont(new Font("Sylfaen", Font.PLAIN, 15));
		lblInsertUserid.setBounds(52, 196, 100, 20);
		add(lblInsertUserid);
		lblInsertUserid.setVisible(false);
		
		lblInsertBookISBN = new JLabel("Insert BookID");
		lblInsertBookISBN.setFont(new Font("Sylfaen", Font.PLAIN, 15));
		lblInsertBookISBN.setBounds(52, 196, 100, 20);
		add(lblInsertBookISBN);
		lblInsertBookISBN.setVisible(false);
		
		
		lblInsertCopyID = new JLabel("Insert CopyID");
		lblInsertCopyID.setFont(new Font("Sylfaen", Font.PLAIN, 15));
		lblInsertCopyID.setBounds(52, 196, 100, 20);
		add(lblInsertCopyID);
		
		
		//search
		btnSearch = new JButton("Search");
		btnSearch.setFont(new Font("Tahoma", Font.PLAIN, 15));
		btnSearch.setBounds(213, 211, 83, 41);
		add(btnSearch);

		//edit
		btnEdit = new JButton("Edit");
		btnEdit.setFont(new Font("Tahoma", Font.PLAIN, 15));
		btnEdit.setBounds(343, 211, 83, 41);
		add(btnEdit);
		btnEdit.setEnabled(false);
		
		
		//add
		btnAdd = new JButton("Add");
		btnAdd.setFont(new Font("Tahoma", Font.PLAIN, 15));
		btnAdd.setBounds(52, 94, 83, 41);
		add(btnAdd);

		
		//remove
		btnRemove = new JButton("Remove");
		btnRemove.setFont(new Font("Tahoma", Font.PLAIN, 14));
		btnRemove.setBounds(466, 211, 83, 41);
		add(btnRemove);
		btnRemove.setEnabled(false);

		
		btnBorrow = new JButton("Borrow");
		btnBorrow.setFont(new Font("Tahoma", Font.PLAIN, 15));
		btnBorrow.setBounds(343, 94, 83, 41);
		add(btnBorrow);
		btnBorrow.setEnabled(false);
		
		btnReturn = new JButton("Return");
		btnReturn.setFont(new Font("Tahoma", Font.PLAIN, 15));
		btnReturn.setBounds(466, 94, 83, 41);
		add(btnReturn);
		btnReturn.setEnabled(false);
		
		btnHistory = new JButton("History");
		btnHistory.setFont(new Font("Tahoma", Font.PLAIN, 15));
		btnHistory.setBounds(213, 95, 83, 41);
		add(btnHistory);
		
		btnHistory.setVisible(false);
				
		searchResultTable.table.setVisible(false);
		searchResultTable.tblScrollPane.setVisible(false);
		
		searchResultTableBook.table.setVisible(false);
		searchResultTableBook.tblScrollPane.setVisible(false);
		
		subscriberUIP = new SubscriberUIP();
		librarianViewHistory = new LibrarianViewHistory(this);
		
		btnClear = new JButton("Clear");
		btnClear.setFont(new Font("Tahoma", Font.PLAIN, 15));
		btnClear.setBounds(52, 519, 83, 41);
		add(btnClear);
		
		Welcome_label = new JLabel("");
		Welcome_label.setFont(new Font("Tahoma", Font.BOLD | Font.ITALIC, 20));
		Welcome_label.setBounds(10, 11, 263, 40);
		add(Welcome_label);
		
		
		
		backgroundlabel = new JLabel("");
		backgroundlabel.setIcon(OBLSettings.IMG_LIBRARIAN_UI);
		backgroundlabel.setBounds(0, 57, 800, 554);
		add(backgroundlabel);

		textField.addActionListener(new ActionListener()
		{
	        public void actionPerformed(ActionEvent e)
	        {
	        	btnSearch.doClick();
	        }  
	    });
// ===========================================================================================
//		 Action Listeners
//     
		tglbtnUsers.addActionListener(new ActionListener() 
		{
			public void actionPerformed(ActionEvent e)
			{
				textField.setText("");
				//remove
				btnRemove.setVisible(false);
				
				//borrow
				btnBorrow.setVisible(false);
				
				//return
				//return
				btnReturn.setVisible(false);
				btnReturn.setEnabled(false);
				
				//edit
				btnEdit.setVisible(true);
				btnEdit.setEnabled(false);
				
				//history
				btnHistory.setVisible(true);
				btnHistory.setEnabled(false);
				
				//search
				btnSearch.setBounds(213, 211, 83, 41);

				//label
				lblInsertUserid.setVisible(true);
				lblInsertBookISBN.setVisible(false);
				lblInsertCopyID.setVisible(false);
				
				//textField 
				textField.setVisible(true);
				
				//table
				searchResultTable.table.setVisible(true);
				searchResultTable.tblScrollPane.setVisible(true);
				searchResultTableCopy.table.setVisible(false);
				searchResultTableCopy.tblScrollPane.setVisible(false);
				searchResultTableBook.table.setVisible(false);
				searchResultTableBook.tblScrollPane.setVisible(false);
				
				flagArr[0] = 1;
				flagArr[1] = 0;
				flagArr[2] = 0;
				}
			});
			
		
//====================================================================================	

		tglbtnBooks.addActionListener(new ActionListener() 
		{
			public void actionPerformed(ActionEvent e) 
			{

				//borrow
				btnBorrow.setVisible(false);
				
				//return
				btnReturn.setVisible(false);
                
				//remove
				btnRemove.setVisible(false);
				btnRemove.setEnabled(false);
				
				//return
				btnReturn.setVisible(false);
				btnReturn.setEnabled(false);
				
				//edit
				btnEdit.setVisible(false);
				
				//search
				btnSearch.setBounds(52, 211, 83, 41);

				
				//history
				btnHistory.setVisible(false);
				
				//textField
				textField.setVisible(false);

				//label
				lblInsertBookISBN.setVisible(false);
				lblInsertUserid.setVisible(false);
				lblInsertCopyID.setVisible(false);
				
				//table
				searchResultTableBook.table.setVisible(true);
				searchResultTableBook.tblScrollPane.setVisible(true);
				searchResultTableCopy.table.setVisible(false);
				searchResultTableCopy.tblScrollPane.setVisible(false);
				searchResultTable.table.setVisible(false);
				searchResultTable.tblScrollPane.setVisible(false);
				
				//array
				flagArr[0] = 0;
				flagArr[1] = 1;
				flagArr[2] = 0;
						
			}
		});
	
//==================================================================================
		tglbtnCopies.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent e) 
			{
				textField.setText("");
				//borrow
				btnBorrow.setVisible(true);
				
				//return
				btnReturn.setVisible(true);
				
				//remove
				btnRemove.setVisible(true);
				btnRemove.setEnabled(false);
				
				//return
				btnReturn.setVisible(true);
				btnReturn.setEnabled(false);
				
				//edit
				btnEdit.setVisible(true);
				btnEdit.setEnabled(false);
				
				//history
				btnHistory.setVisible(false);
				
				//search
				btnSearch.setBounds(213, 211, 83, 41);


				lblInsertUserid.setVisible(false);
				lblInsertBookISBN.setVisible(false);
				lblInsertCopyID.setVisible(true);
				
				//textField 
				textField.setVisible(true);
				
				//array
				flagArr[0] = 0;
				flagArr[1] = 0;
				flagArr[2] = 1;			
				
				//table
				searchResultTable.table.setVisible(false);
				searchResultTable.tblScrollPane.setVisible(false);
				searchResultTableCopy.table.setVisible(true);
				searchResultTableCopy.tblScrollPane.setVisible(true);
				searchResultTableBook.table.setVisible(false);
				searchResultTableBook.tblScrollPane.setVisible(false);
				
			}
		});
		
//==================================================================================
		btnAdd.addActionListener(new ActionListener() 
		{
			public void actionPerformed(ActionEvent e1) 
			{
				
				 if(flagArr[0]==1)
				 {
					op_user = "AddUser";
					librarianAddEditUserPanel.txtAddUserIDField.setText(null);
					librarianAddEditUserPanel.txtFirstNameField.setText(null);
					librarianAddEditUserPanel.txtLastNameField.setText(null);
					librarianAddEditUserPanel.txtPhoneNumField.setText(null);
					librarianAddEditUserPanel.txtStatusField.setText(null);
					librarianAddEditUserPanel.txtAddressField.setText(null);
					librarianAddEditUserPanel.txtEmailField.setText(null);
					librarianAddEditUserPanel.txtAddUserIDField.setText(null);
					librarianAddEditUserPanel.txtAddUserIDField.enable();
					librarianAddEditUserPanel.txtStatusField.setVisible(false);
					librarianAddEditUserPanel.lblStatus.setVisible(false);
	                librarianAddEditUserPanel.lblTitleLabel.setText("OBL   Add New User");
	                librarianAddEditUserPanel.btnUserOperation.setText("Add User");
	                WelcomeUI.wui.switchPanel("OBL - Add User", librarianAddEditUserPanel,OBLSettings.pane2Size[0], OBLSettings.pane2Size[1]);
				 }
			
				 else if (flagArr[1]==1)
				 {
					 op_Book = "AddBook";
					 librarianAddEditBookPanel.rdbtnAddNewSubject.setVisible(true);
					 librarianAddEditBookPanel.lblTitleLabel.setText("OBL - Add New Book");
                     librarianAddEditBookPanel.btnBookOperation.setText("Add Book");
					 WelcomeUI.wui.switchPanel("OBL - Add Book", librarianAddEditBookPanel,OBLSettings.pane2Size[0], OBLSettings.pane2Size[1]); 
				 }
				 else if (flagArr[2]==1)
				 {
						op_Copy = "AddCopy";
					    librarianAddEditCopyPanel.lblTitleLabel.setText("OBL - Add Copy");
	                    librarianAddEditCopyPanel.btnCopyOperation.setText("Add Copy");
					    WelcomeUI.wui.switchPanel("OBL - Add Copy", librarianAddEditCopyPanel,OBLSettings.pane2Size[0], OBLSettings.pane2Size[1]);
				 }
				 
			}
		});
//==================================================================================		
		btnEdit.addActionListener(new ActionListener() 
		{
			public void actionPerformed(ActionEvent e) 
			{
				  if(flagArr[0]==1)
				   {
					 op_user = "EditUser";
					 librarianAddEditUserPanel.txtStatusField.setVisible(true);
					 librarianAddEditUserPanel.lblStatus.setVisible(true);
                     librarianAddEditUserPanel.btnUserOperation.setText("Edit User");
                     librarianAddEditUserPanel.lblTitleLabel.setText("OBL - Edit User");
                     WelcomeUI.wui.switchPanel("OBL - Edit User", librarianAddEditUserPanel,OBLSettings.pane2Size[0], OBLSettings.pane2Size[1]);
				   }
				  else if(flagArr[1]==1)
				  {
					  op_Book = "EditBook";
					  librarianAddEditBookPanel.lblTitleLabel.setText("OBL - Edit Book");
	                  librarianAddEditBookPanel.btnBookOperation.setText("Edit Book");
                      WelcomeUI.wui.switchPanel("OBL - Edit Book", librarianAddEditBookPanel,OBLSettings.pane2Size[0], OBLSettings.pane2Size[1]);  
				  }
				  else if (flagArr[2]==1)
				  {
					  op_Copy = "EditCopy";
					  librarianAddEditCopyPanel.lblTitleLabel.setText("OBL - Edit Copy");
                      librarianAddEditCopyPanel.btnCopyOperation.setText("Edit Copy");
                      WelcomeUI.wui.switchPanel("OBL - Edit Copy", librarianAddEditCopyPanel,OBLSettings.pane2Size[0], OBLSettings.pane2Size[1]);

				  }

			}
		});
//==========================================================================================
		btnSearch.addActionListener(new ActionListener() 
		{
			public void actionPerformed(ActionEvent e) 
			{
				
				 if(flagArr[0]==1)  //userButton
				 {
					 
					String userID=getINFO();
	                LibrarianSearchUserMessage librarianSearchUserMsg = new LibrarianSearchUserMessage(userID);
	                if (userID.isEmpty())
	                {
                        JOptionPane.showMessageDialog( WelcomeUI.wui, "The field UserID is empty .\n Please enter user ID " 
                                        ,"Warning",JOptionPane.WARNING_MESSAGE);
                        searchResultTable.model.setRowCount(0);         
	                }
	                else   //userID not empty
	                {       
                        librarianSearchUserMsg = luip.librarianSearchUser(userID);
                       
                        //user Doesn't exist
                        if (librarianSearchUserMsg.getQueryUserSearchResult() == -2)
                        {
                        	JOptionPane.showMessageDialog( WelcomeUI.wui, "The user doesn't exist" ,
                        			"Warning",JOptionPane.WARNING_MESSAGE);
                        	searchResultTable.model.setRowCount(0);
                        	btnHistory.setEnabled(false);
                        	btnEdit.setEnabled(false);
                        }
                        
                        //error in db
                        else if (librarianSearchUserMsg.getQueryUserSearchResult()==-3)
                        {
                                JOptionPane.showMessageDialog( WelcomeUI.wui, "There was an error in search user" ,
                                        "Warning",JOptionPane.WARNING_MESSAGE);                                  
                                searchResultTable.model.setRowCount(0);
                        }
                        else
                        {
                                //JOptionPane.showMessageDialog( WelcomeUI.wui, " Search succeded ","Done",JOptionPane.INFORMATION_MESSAGE);
                                String usrStatus="";
        						int userStatus=librarianSearchUserMsg.getUser().getStatus();
        						int userPermission=librarianSearchUserMsg.getUser().getPermmision();
        						if (userPermission==5)
        							usrStatus="Suspend";
        						else if (userStatus==2)
        							usrStatus="Lock";
        						else 
        							usrStatus="Active";	
                                //print the resultinto table
                                searchResultTable.model.addRow(new Object[] {librarianSearchUserMsg.getUser().getID(),librarianSearchUserMsg.getUser().getFname(),librarianSearchUserMsg.getUser().getLname(),librarianSearchUserMsg.getUser().getAddress(),librarianSearchUserMsg.getUser().getEmail()
                                        ,librarianSearchUserMsg.getUser().getPhone(),usrStatus});
                                searchResultTable.table.repaint();
                        }
	                }       
	
				 }//if
				 else if(flagArr[1]==1)//book panel
				 { 
					 WelcomeUI.wui.switchPanel("OBL - Search Book", librarianSearchBookPanel ,OBLSettings.pane2Size[0], OBLSettings.pane2Size[1]);
					 librarianSearchBookPanel.searchByBookNameFiled.grabFocus();
				 }
				 
				 else  if(flagArr[2]==1)  //copy panel
				 {
					    
					 	String copyID=getINFO();
		                LibrarianSearchCopyMessage librarianSearchCopyMsg = new LibrarianSearchCopyMessage(copyID);
		                if (copyID.isEmpty())
		                {
	                        JOptionPane.showMessageDialog( WelcomeUI.wui, "The field CopyID is empty .\n Please enter user ID " 
	                                        ,"Warning",JOptionPane.WARNING_MESSAGE);
	                        searchResultTableCopy.model.setRowCount(0);         
		                }
		                else   //userID not empty
		                {       
		                	librarianSearchCopyMsg = luip.librarianSearchCopy(copyID);
	                       
	                        //user Doesn't exist
	                        if (librarianSearchCopyMsg.getQueryCopySearchResult() == -2)
	                        {
	                        	JOptionPane.showMessageDialog( WelcomeUI.wui, "The copy doesn't exist" ,
	                        			"Warning",JOptionPane.WARNING_MESSAGE);
	                        	searchResultTableCopy.model.setRowCount(0);
	                        	btnBorrow.setEnabled(false);
	                        	btnEdit.setEnabled(false);
	                        	btnRemove.setEnabled(false);
	                        	btnReturn.setEnabled(false);
	                        }
	                        
	                        //error in db
	                        else if (librarianSearchCopyMsg.getQueryCopySearchResult()==-3)
	                        {
	                                JOptionPane.showMessageDialog( WelcomeUI.wui, "There was an error in search copy" ,
	                                        "Warning",JOptionPane.WARNING_MESSAGE);                                  
	                                searchResultTableCopy.model.setRowCount(0);
	                        }
	                        else
	                        {	
	                                //print the result into table
	                                searchResultTableCopy.model.addRow(new Object[] {librarianSearchCopyMsg.getCopy().getCopyID(),librarianSearchCopyMsg.getCopy().getCopyOfISBN(),librarianSearchCopyMsg.getCopy().getBorrow(),librarianSearchCopyMsg.getCopy().getPurchaseDate() });
	                                searchResultTableCopy.table.repaint();
	                        }
		                }       

				 }
			}
		
	
		});
//==========================================================================================		
		btnReturn.addActionListener(new ActionListener() 
		{
			public void actionPerformed(ActionEvent arg0) 
			{
				
				int row=searchResultTableCopy.table.getSelectedRow();
				String copyID=(String) searchResultTableCopy.model.getValueAt(row, 0);
				String borrow=(String) searchResultTableCopy.model.getValueAt(row, 2);
				if (borrow.equals("0"))
					JOptionPane.showMessageDialog( WelcomeUI.wui, "The copy is not borrowed! ","Warning",JOptionPane.WARNING_MESSAGE);
				else if (borrow.equals("1"))
				{
					int returnBookResult = luip.librarianReturnBook(copyID, -10);
					switch (returnBookResult)
					{
					
						case 1: // copy remove successfully
						{
							//add action that clean the  table
					
							JOptionPane.showMessageDialog( WelcomeUI.wui, "The copy was returned successfully!","Return Copy",JOptionPane.INFORMATION_MESSAGE);
							searchResultTableCopy.table.setValueAt("0",row, 2);
							break;
						} 
						case -1: // copy is borrowed
						{
							JOptionPane.showMessageDialog( WelcomeUI.wui, "The copy is not borrowed! ","Warning",JOptionPane.WARNING_MESSAGE);
							break;
						}
						default: // Error
						{
							JOptionPane.showMessageDialog( WelcomeUI.wui, "Operation failed!","Warning",JOptionPane.ERROR_MESSAGE);				
							break;
						}
				  } // switch
				
				}//else
				
			}
		});
//==========================================================================================
		btnBorrow.addActionListener(new ActionListener() 
		{
			public void actionPerformed(ActionEvent arg0) 
			{
				int row = searchResultTableCopy.table.getSelectedRow();
				if (row >= 0)
				{
					// Get row data
					String copy_id = searchResultTableCopy.table.getValueAt(row, 0).toString();
					String isbn = searchResultTableCopy.table.getValueAt(row, 1).toString();
					String user_id = JOptionPane.showInputDialog( WelcomeUI.wui, "Please enter the subscriber ID:","Borrow a book",JOptionPane.INFORMATION_MESSAGE);
					int bres = -99;
					try
					{
						bres = luip.borrowCopy(isbn, copy_id, new User(user_id,"","first-name","last-name","","","",0,0));
					}
					catch (NullPointerException e)
					{
						bres = -99;
					}
					switch (bres)
					{
						case -99:
						{
							JOptionPane.showMessageDialog( WelcomeUI.wui, "Operation Failed!","Error",JOptionPane.ERROR_MESSAGE);
							break;
						}
						case -10:
						{
							JOptionPane.showMessageDialog( WelcomeUI.wui, "Error! This copy is reported lost!","Error",JOptionPane.ERROR_MESSAGE);
							break;
						}						
						case -9:
						{
							JOptionPane.showMessageDialog( WelcomeUI.wui, "Error! User is not a subscriber!","Error",JOptionPane.ERROR_MESSAGE);
							break;
						}						
						case -8:
						{
							JOptionPane.showMessageDialog( WelcomeUI.wui, "Error! User not found!","Error",JOptionPane.ERROR_MESSAGE);
							break;
						}
						case -7:
						{
							JOptionPane.showMessageDialog( WelcomeUI.wui, "Error! Input failure!","Error",JOptionPane.ERROR_MESSAGE);
							break;
						}
						case -6:
						{
							JOptionPane.showMessageDialog( WelcomeUI.wui, "Sorry, Couldn't delete the user's order!","Error",JOptionPane.ERROR_MESSAGE);
							break;
						}
						case -5:
						{
							JOptionPane.showMessageDialog( WelcomeUI.wui, "Sorry, There are earlier orders for this book.","Error",JOptionPane.ERROR_MESSAGE);
							break;
						}
						case -4:
						{
							JOptionPane.showMessageDialog( WelcomeUI.wui, "Error! This copy is already borrowed","Error",JOptionPane.ERROR_MESSAGE);
							break;
						}
						case -3:
						{
							JOptionPane.showMessageDialog( WelcomeUI.wui, "Sorry, the user already has this book.","Error",JOptionPane.ERROR_MESSAGE);
							break;
						}
						case -2:
						{
							JOptionPane.showMessageDialog( WelcomeUI.wui, "Sorry, User is suspended!","Error",JOptionPane.ERROR_MESSAGE);
							break;
						}
						case -1:
						{
							JOptionPane.showMessageDialog( WelcomeUI.wui, "Sorry, User is locked!","Error",JOptionPane.ERROR_MESSAGE);
							break;
						}
						case 1:
						{
							JOptionPane.showMessageDialog( WelcomeUI.wui, "Borrowed successfully!","Success",JOptionPane.INFORMATION_MESSAGE);
							searchResultTableCopy.table.setValueAt("1",row, 2);
							break;
						}
					} // End of switch
				}	// End of if
				else
				{
					JOptionPane.showMessageDialog( WelcomeUI.wui, "Please select a copy to borrow!","Error",JOptionPane.ERROR_MESSAGE);
				}
			}
		});
		
//===========================================================================================
		searchResultTable.table.getSelectionModel().addListSelectionListener(new ListSelectionListener() 
		{
			public void valueChanged(ListSelectionEvent e) 
			{
				JTable table = searchResultTable.table;

				if(table.getRowCount() > 0)	
				{	
					
					int row = searchResultTable.table.getSelectedRow();
					String userID=getINFO();
					LibrarianSearchUserMessage librarianSearchUserMsg = new LibrarianSearchUserMessage(userID);
					if(row>=0)
					{ 
						btnEdit.setEnabled(true);
						btnHistory.setEnabled(true);
						librarianSearchUserMsg = luip.librarianSearchUser(userID);
						librarianAddEditUserPanel.txtAddUserIDField.setText(librarianSearchUserMsg.getUser().getID());
						librarianAddEditUserPanel.txtAddUserIDField.disable();
						librarianAddEditUserPanel.txtFirstNameField.setText(librarianSearchUserMsg.getUser().getFname());
						librarianAddEditUserPanel.txtLastNameField.setText(librarianSearchUserMsg.getUser().getLname());
						librarianAddEditUserPanel.txtEmailField.setText(librarianSearchUserMsg.getUser().getEmail());
						librarianAddEditUserPanel.txtPhoneNumField.setText(librarianSearchUserMsg.getUser().getPhone());
						librarianAddEditUserPanel.txtAddressField.setText(librarianSearchUserMsg.getUser().getAddress());
						String usrStatus="";
						int userStatus=librarianSearchUserMsg.getUser().getStatus();
						int userPermission=librarianSearchUserMsg.getUser().getPermmision();
						if (userPermission==5)
							usrStatus="Suspend";
						else if (userStatus==2)
							usrStatus="Lock";
						else 
							usrStatus="Active";	
						librarianAddEditUserPanel.txtStatusField.setText(usrStatus);
						librarianAddEditUserPanel.txtStatusField.disable();
			    		
					}
				} 
				else 
				{
					btnEdit.setEnabled(false);
					btnHistory.setEnabled(false);
				}
;
			}
			
		});
	
//========================================================================================
		searchResultTableCopy.table.getSelectionModel().addListSelectionListener(new ListSelectionListener() 
		{
			public void valueChanged(ListSelectionEvent e) 
			{
				JTable table = searchResultTableCopy.table;

				if(table.getRowCount() > 0)	
				{	
					
					int row = searchResultTableCopy.table.getSelectedRow();
					String copyID=getINFO();
					LibrarianSearchCopyMessage librarianSearchCopyMessage = new LibrarianSearchCopyMessage(copyID);
					if(row>=0)
					{ 
						btnEdit.setEnabled(true);
						btnRemove.setEnabled(true);
						btnBorrow.setEnabled(true);
						btnReturn.setEnabled(true);
						librarianSearchCopyMessage = luip.librarianSearchCopy(copyID);
						librarianAddEditCopyPanel.txtCopyID.setText(librarianSearchCopyMessage.getCopy().getCopyID());
						librarianAddEditCopyPanel.txtCopyID.disable();
						librarianAddEditCopyPanel.txtISBN.setText(librarianSearchCopyMessage.getCopy().getCopyOfISBN());
						librarianAddEditCopyPanel.txtISBN.disable();
						librarianAddEditCopyPanel.txtPurchaseDate.setText(librarianSearchCopyMessage.getCopy().getPurchaseDate());
						String usrStatus="";
						usrStatus=librarianSearchCopyMessage.getCopy().getBorrow();
						
						if (usrStatus.equals("1"))
							usrStatus="Borrow";
						else if (usrStatus.equals("0"))
							usrStatus="Not Borrow";
						librarianAddEditCopyPanel.txtBorrow.setText(usrStatus);
						librarianAddEditCopyPanel.txtBorrow.disable();
	
					}
				}
				else 
				{
					btnEdit.setEnabled(false);
					btnRemove.setEnabled(false);
					btnBorrow.setEnabled(false);
					btnReturn.setEnabled(false);
				}
			}
			
		});
//====================================================================================		
		btnHistory.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent e) 
			{
			
				librarianViewHistory.showHistory(textField.getText());
				WelcomeUI.wui.switchPanel("OBL View History", librarianViewHistory , OBLSettings.pane2Size[0], OBLSettings.pane2Size[1]);
				
			}
		});
		
		
//=====================================================================================
		btnRemove.addActionListener(new ActionListener() 
		{
			public void actionPerformed(ActionEvent arg0)
			{
			
				if(flagArr[2]==1)  //copyButton
				{
					if (JOptionPane.showConfirmDialog(WelcomeUI.wui,"Are you sure?", "Quitting",JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)
					{
					
						//add message that remove book
						int rowCopy = searchResultTableCopy.table.getSelectedRow();
						int removeCopyRes=luip.librarianRemoveCopy((String)searchResultTableCopy.model.getValueAt(rowCopy,0));
								                                	
					  switch (removeCopyRes)
					  {
						
						case 1: // copy remove successfully
						{
							//add action that clean the  table
						
							JOptionPane.showMessageDialog( WelcomeUI.wui, "Copy removed successfully!","Remove Copy",JOptionPane.INFORMATION_MESSAGE);
							break;
						} 
						case -1: // copy is borrowed
						{
							JOptionPane.showMessageDialog( WelcomeUI.wui, "You Can't delete this copy! The copy is borrowed ","Warning",JOptionPane.WARNING_MESSAGE);
							break;
						}
						default: // Error
						{
							JOptionPane.showMessageDialog( WelcomeUI.wui, "Operation failed!","Warning",JOptionPane.ERROR_MESSAGE);				
							break;
						}
					  } // switch
	
					}//if
				}//if button
				
			} //method
		});
	
	
//==============================================================================================
		btnClear.addActionListener(new ActionListener() 
		{
			public void actionPerformed(ActionEvent arg0) 
			{
				if(flagArr[0]==1)  //userButton
				{
					searchResultTable.model.setRowCount(0);
					textField.setText(null);
				}
				if(flagArr[1]==1)  //bookButton
				{
					searchResultTableBook.model.setRowCount(0);
					textField.setText(null);
				}
				if(flagArr[2]==1)  //copyButton
				{
					searchResultTableCopy.model.setRowCount(0);
					textField.setText(null);
				}
			
			}
		});
			
	}//initialize


//====================================================================================	
//	                       Getters & Setters
//
	
	public String getINFO()
	{
		return textField.getText();

	}
	public void setINFO(JTextField textField)
	{
		this.textField = textField;
	}
	
	public LibrarianUI getLibrarianUI()
	{
		return this;
	}
	
	public LibrarianUIP getLuip() 
	{
		return luip;
	}
	
	public void paintComponent(Graphics g) 
	{
		g.drawImage((OBLSettings.IMG_DEFAULT_BACKGROUND).getImage(), 0, 0, OBLSettings.pane2Size[0], OBLSettings.pane2Size[1],null);
		
	}
}
